<?php
require_once(__DIR__ . '/configuracion.php');
require_once(__DIR__.'/utilidades.php');
  
//define("DBHOST", "localhost");
//define("DBNAME", "u661954954_at");
//define("DBUSER", "u661954954_at");
//define("DBPASS", "u661954954");
            
function check_user($username,$password) {
    // Define $username and $password
            $username = $_REQUEST['username'];
            $password = $_REQUEST['password'];
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
            
            $db = new PDO("mysql:dbname=" . DBNAME . ";host=" . DBHOST, DBUSER, DBPASS);
            $db->exec("SET CHARACTER SET utf8");
            $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// To protect MySQL injection for Security purpose
            $username = stripslashes($username);
            $password = stripslashes($password);
// SQL query to fetch information of registerd users and finds user match.
            $resul = $db->query("select * from usuario,rol_usuario where id=idusuario and password='$password' AND login='$username'");
            $rows = $resul->rowCount();
            if ($rows >= 1) {               
                //print_r($resul);
                $_SESSION['username'] = $username; // Initializing Session
                foreach ($resul as $k=>$v) {
                    //print ("k=" . $k . " " . "v=" . $v['rol'] ."<br>");
                    //print_r($v);
                    $_SESSION['roles'][]=$v['rol'];
                }
                header("location: " . $_SESSION['afterLogin']); // Redirecting To Other Page
                return "";
            } else {
                $error = "Contraseña o nombre de usuario invalidos";
            }
            print $error;
            $db=null; // Closing Connection 
            return $error;
}

function isUserInRol($user,$rol) {
    //print "Buscando " . $rol . " en " . print_r($_SESSION['roles']);
    $i=array_search($rol,$_SESSION['roles']);
    return $rol==$_SESSION['roles'][$i];

}


function rolOK($userroles,$rolesConAcceso){
    foreach ($userroles as $rol){
        $i=array_search($rol,$rolesConAcceso);
        if ($rol == $rolesConAcceso[$i]){
            return TRUE;
        }
    }
    return FALSE;
}


function operatorRolIn($prefijo){
    $result = '(0';
    foreach ($_SESSION['roles'] as $rol) {
        //print $rol . " -> " . stripos($rol,$prefijo) . " <-<br>";
        
        if (stripos($rol,$prefijo)!==FALSE) {            
            $result .= ',' . substr($rol, strlen($prefijo));
        }
    }
    $result .= ')';
    return $result;
}


